/**
 * Copyrights@2006, Tianyuan DIC Information Co.,Ltd.
 * 文件名:    TMallPayHandle.java
 * 描述:
 * 作者:     kaiyang
 * 版本:    1.0
 * 创建时间:   2015年5月4日 上午11:57:29
 * <p>
 * 修改历史:
 * 日期                          作者           版本         描述
 * ------------------------------------------------------------------
 * 2015年5月4日      kaiyang      1.0        1.0 Version
 */
package com.hp.bon.sgw.wh.channel.handler;

import com.hp.bon.omc.util.StringUtil;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.bean.tmall.FixedBroadbandBean;
import com.hp.bon.sgw.wh.channel.TMallChannel;
import com.hp.bon.sgw.wh.service.TMallResponseService;
import com.hp.bon.sgw.wh.service.TmallLogDao;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.utils.ResultCodeUtil;
import com.hp.bon.sgw.wh.utils.SignUtilsImpl;
import com.hp.ocs.diameter.message.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * @ClassName: TMallPayHandle
 * @Description: TODO
 * @author: kaiyang
 * @date:2015年5月4日 上午11:57:29     
 */
public class FixedBroadbandHandler2 implements IAsynCallHandler {

    private static final Logger _log = LoggerFactory.getLogger(TaobaoFeeHandle.class);
    private PrintStream printStream;
    private FixedBroadbandBean taobaoPayBean;
    private TMallResponseService tmallResponseService;
    private ThreadPoolTaskExecutor asynExecutor;
    private String pubKeyValue;
    private UserResourceConfigService userResourceConfigService;
//	private TmallLogDao tmallLogDao;

    public FixedBroadbandHandler2(PrintStream printStream, FixedBroadbandBean taobaoPayBean, TMallResponseService tmallResponseService,
                                  ThreadPoolTaskExecutor asynExecutor, String pubKeyValue, TmallLogDao tmallLogDao) {
        this.printStream = printStream;
        this.taobaoPayBean = taobaoPayBean;
        this.tmallResponseService = tmallResponseService;
        this.asynExecutor = asynExecutor;
        this.pubKeyValue = pubKeyValue;
    }

    @Override
    public int getProtocolType() {
        return 0;
    }

    @Override
    public void onCallResult(CallParam callParam) {
        XmlMessage ack = null;
        Object response = null;
        if (callParam.getResponse() != null) {
            response = callParam.getResponse();
        } else if (callParam.getRecvResponse() != null) {
            response = callParam.getRecvResponse();
        }
        if (response == null) {
            int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
            ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
            callParam.setServiceResultCode(_retcodeTmp);//11203
        } else {
            if (response instanceof Message) {
                ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
            } else if (response instanceof XmlMessage) {
                ack = (XmlMessage) response;
            } else {
                _log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
            }
        }
        try {
            String respXML = convertResponseString((Message) response, callParam.getServiceResultCode());
            byte[] resp = respXML.getBytes("UTF-8");
            ack.setLength(resp.length);
            ack.setMsgTime(System.currentTimeMillis());
            printStream.write(resp);
            printStream.close();
            callParam.setResponse(ack);
            if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
                MessageDetail detail = new MessageDetail();
                detail.setBusinessCallId(callParam.getBussinessCallId());
                detail.setSessionId(callParam.getSessionId());
                detail.setServiceContextId(callParam.getServiceContextId());
                detail.setMessageType(MessageType.WSA);
                detail.setDetails(ack.getDATA());
                detail.setMsgTime(new Date(ack.getMsgTime()));
                detail.setOpType("send");
                detail.setHostId(callParam.getUserName());
                MessageDetailCacheManager.getInstance().add(detail);
            }
            TaskManager.taskProcess(callParam);
            _log.info("http response(taobao) " + respXML);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private String convertResponseString(Message answer, int serviceResultCode) {
        _log.info("FixedBroadbandHandler convertResponseString serviceResultCode = {}", serviceResultCode);
        String response = "";
        String billSerialNbr = "";
        String pfr = "";
        int Result=-1;
        Map<String, String> data = new HashMap<String, String>();
        data.put("tbOrderNo", taobaoPayBean.getTbOrderNo());
        data.put("bizType", taobaoPayBean.getBizType());
        try {
            //充值成功 service_infomation
            AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION, Constants.DIAMETER_VENDOR_3GPP);
            AVP_Grouped avpServiceInfomation = new AVP_Grouped(avp);
            //Bill_Serial_Nbr
            AVP avpBillSerialNbr = avpServiceInfomation.find(80133, Constants.DIAMETER_VENDOR_CT);
            if (avpBillSerialNbr != null)
                billSerialNbr = new AVP_UTF8String(avpBillSerialNbr).queryValue();
            AVP Result_AVP = avpServiceInfomation.find(20631, Constants.DIAMETER_VENDOR_CT);
            if (Result_AVP != null)
                Result = new AVP_Unsigned32(Result_AVP).queryValue();
            AVP Para_Field_Result_AVP = avpServiceInfomation.find(80407, Constants.DIAMETER_VENDOR_CT);
            if (Para_Field_Result_AVP != null)
                pfr = new AVP_UTF8String(Para_Field_Result_AVP).queryValue();
        } catch (Exception e) {
            _log.info("Exception ", e);
        }

        if(StringUtil.isBlank(billSerialNbr)){
            billSerialNbr=taobaoPayBean.getTbOrderNo();
        }
        data.put("coopOrderNo", billSerialNbr);
        userResourceConfigService = SpringContext.getApplicationContext().getBean(UserResourceConfigService.class);
        String newCode = ResultCodeUtil.updateResultCode(serviceResultCode, userResourceConfigService.getValue("taobao_resultCode"), userResourceConfigService.getValue("taobao_defaultResult"));
        data.put("errCode", newCode);

        if(answer == null || Result==-1 || serviceResultCode==571){
            //无响应
            data.put("coopOrderStatus", TMallChannel.STATUS_UNDERWAY);
            data.put("errDesc", "");
            data.put("errCode", "");
        }else if (serviceResultCode == 0) {
            data.put("coopOrderStatus", TMallChannel.STATUS_SUCCESS);
            data.put("errDesc", "");
            data.put("errCode", "");
        } else{
            //充值失败
            data.put("coopOrderStatus", TMallChannel.STATUS_FAIL);
            if(StringUtil.isBlank(pfr)){
                pfr="其他异常";
            }
            data.put("errDesc", pfr);
        }
        String coopOrderStatus = data.get("coopOrderStatus");
        if(!TMallChannel.STATUS_UNDERWAY.equals(coopOrderStatus)){
            //充值中 需要通知淘宝来扫描
            TreeMap<String, String> paraMap = new TreeMap<String, String>();
            paraMap.put("tbOrderNo", taobaoPayBean.getTbOrderNo());
            paraMap.put("bizType", taobaoPayBean.getBizType());
            paraMap.put("supplierId", taobaoPayBean.getSupplierId());
            paraMap.put("ts", System.currentTimeMillis() + "");
            paraMap.put("errCode", data.get("errCode"));
            paraMap.put("coopOrderNo", data.get("coopOrderNo"));
            paraMap.put("coopOrderStatus", data.get("coopOrderStatus"));
            paraMap.put("errDesc", data.get("errDesc"));
            String source = "";
            for (Entry<String, String> entry : paraMap.entrySet()) {
                if (entry.getValue() != null && !"".equals(entry.getValue())) {
                    source += entry.getKey() + entry.getValue();
                }
            }
            source = source + pubKeyValue;
            String sign = SignUtilsImpl.getTmallSign(source);
            paraMap.put("sign", sign);
            TaobaoRetTask task = new TaobaoRetTask(taobaoPayBean.getNotifyUrl(), paraMap);
            asynExecutor.execute(task);
        }

        response = tmallResponseService.getResponse1(data);
        return response;
    }
}
